/**
 * @Author yinyunqi
 * @date 2018年2月1日
 * @Content 
 */
package com.yongqi.controller.back;

import static org.hamcrest.CoreMatchers.nullValue;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.yongqi.model.Family;
import com.yongqi.model.Menu;
import com.yongqi.service.MenuService;
import com.yongqi.shiro.UsernamePasswordUsertypeToken;

@Controller
@RequestMapping("/back")
public class BackHomeController {
    @Autowired
    MenuService menuService;
    /**
     * 后台登录页面
     * @return
     */
    
    @RequestMapping("/login")
    public String backLogin() {
	return "back/back_login";
    }
    /**
     * 后台登录验证
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value="loginValidate")
    public String loginValidate(HttpServletRequest request) {
	String familyAccount = request.getParameter("username");
	String password = request.getParameter("password");
	String usertype = "back";
	UsernamePasswordUsertypeToken token = new UsernamePasswordUsertypeToken(familyAccount, password, usertype);
	String result = "";
	try {
	    SecurityUtils.getSubject().login(token);
	    result = "success";
	    
	}catch (UnknownAccountException e) {
	    result = "errorusername";
	}catch (IncorrectCredentialsException e) {
	    result = "errorpassword";
	}
	JSONObject object = new JSONObject();
	object.put("result", result);
	return object.toJSONString();
    }
    /**
     * 登录成功后台主页面
     * @return
     */
    @RequiresRoles("ADMIN")
    @RequestMapping("/index")
    public String backIndex(Model model) {
    	Family family = (Family)SecurityUtils.getSubject().getPrincipal();
    	if (family.getLevel().equals("front")) {
			return "noPermission";
		}
		List<Menu> backMenuList = menuService.getBackMenu();
		model.addAttribute("backMenuList", backMenuList);
		return "back/back_index";
    }
}

